package com.innovation.chengzhangriji.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverPhoto;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.ui.adapter.DTAdapter;
import com.innovation.chengzhangriji.ui.agent.DiscoverTimelineAgent;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.innovation.chengzhangriji.ui.event.BaseTimelineEvent;
import com.innovation.chengzhangriji.ui.model.DTModel;
import com.innovation.chengzhangriji.ui.widget.CuteBabyAvatarView;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.ExtraSwipeRefreshLayout;
import com.innovation.chengzhangriji.ui.widget.TimeLineBarView;
import com.innovation.chengzhangriji.util.BabyUtil;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.orhanobut.logger.Logger;

import org.apache.http.Header;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import de.greenrobot.event.Subscribe;

public class DiscoverTimelineActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, DTAdapter.DTAdapterAgent, TimeLineBarView.SendMessageListener, TimeLineBarView.ExecuteListener, TimeLineBarView.RecordListener, ExtraSwipeRefreshLayout.OnRefreshListener, CuteToolbar.OnDoubleClickListener, View.OnClickListener, View.OnTouchListener {

    private CuteToolbar mToolbar;

    private ExtraSwipeRefreshLayout swipe;

    private RecyclerView recyclerView;

    private CuteBabyAvatarView avatarView;

    private TimeLineBarView timeLineBarView;

    private DTAdapter adapter;

    // 媒体播放
    private MediaPlayer player;

    private CuteTextView txtBabyName, txtBabyAge, txtFixedDate, txtFixedDay;

    private int height = 0;

    // 停靠的日期栏
    private View fixedDateLayout;

    // 数据代理
    private DiscoverTimelineAgent agent;

    private View emptyView;

    // 评论输入区域
    private RelativeLayout commentLayout;
    private EditText editComment;

    // 当前宝宝的关注人
    private Parent[] parents;

    // 宝宝的日记的查看权限
    private BabyAndParent babyAndParent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 修改线程策略，让主线程能访问网络
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        setContentView(R.layout.activity_discover_timeline);

        int babyId = mLoginInfo.getBabyID();
        agent = new DiscoverTimelineAgent(this, babyId);
        // 设置当前宝宝
        mLoginInfo.setBabyID(babyId);
        String loginValue = new Gson().toJson(mLoginInfo);
        Config.setLoginInfo(this, loginValue);

        // 当前宝宝的关注人
        parents = DatabaseManager.getInstance(this).queryParent(agent.getBaby().getBabyID());

        // 宝宝日记的查看权限
        babyAndParent = DatabaseManager.getInstance(this).queryBabyAndParent(mLoginInfo.getUserID(), mLoginInfo.getBabyID());
        if(babyAndParent == null) {
            tipShow("你已取消对该宝宝的关注!");
            finish();
            return;
        }

        // 初始化布局
        setupLayout();
    }

    // 初始化布局
    private void setupLayout() {
        mToolbar = (CuteToolbar) findViewById(R.id.toolbar_layout);
        mToolbar.setCuteTitle("");
        mToolbar.setOnClickCuteToolbarListener(this);
        mToolbar.setOnDoubleClickListener(this);

        // 停靠的日期
        fixedDateLayout = findViewById(R.id.date_layout);
        txtFixedDate = (CuteTextView) findViewById(R.id.text_date);
        txtFixedDay = (CuteTextView) findViewById(R.id.text_day);

        // 宝宝头像
        avatarView = (CuteBabyAvatarView) findViewById(R.id.image_baby_head);

        // 宝宝姓名
        txtBabyName = (CuteTextView) findViewById(R.id.text_baby_name);

        // 宝宝年龄
        txtBabyAge = (CuteTextView) findViewById(R.id.text_baby_age);

        // 空布局
        emptyView = findViewById(R.id.empty_view);

        swipe = (ExtraSwipeRefreshLayout) findViewById(R.id.swipe);
//        swipe.setColorSchemeResources(
//                android.R.color.holo_blue_light,
//                android.R.color.holo_red_light,
//                android.R.color.holo_orange_light,
//                android.R.color.holo_green_light);
        swipe.setOnRefreshListener(this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new DTAdapter(this, this);
        recyclerView.setAdapter(adapter);
        recyclerView.setOnTouchListener(this);
        recyclerView.setOnScrollListener(new ExtraOnScrollListener());
        swipe.setRefreshTarget(recyclerView);
        swipe.setNestedScrollLayout(R.id.nestLayout);
//        swipe.setSwipeableChildren(R.id.recycler);

        // 发表日记的 bottomBar
        timeLineBarView = (TimeLineBarView) findViewById(R.id.timeline_bar);
        timeLineBarView.setSendMessageListener(this);
        timeLineBarView.setExecuteListener(this);
        timeLineBarView.setRecordListener(this);

        // 发表日记的 bottom
        commentLayout = (RelativeLayout) findViewById(R.id.layout_bottom);
        editComment = (EditText) findViewById(R.id.edit_comment);
        ImageView buttonComment = (ImageView) findViewById(R.id.button_comment);
        buttonComment.setOnClickListener(this);

        // 设置 recyclerView 位置
        showTimelinebarView();

        // 刷新数据
        agent.loadLocalTopNewDiary();
        if(agent.getDiscoverList().size() > 0) {
            if(agent.getDiscoverList().size() < Config.QUERY_LENGTH) {
                adapter.setEnd(true);
            }
            emptyView.setVisibility(View.GONE);
        } else {
            if(!Client.isNetworkConnect(this)) {
                emptyView.setVisibility(View.VISIBLE);
            }
        }
        adapter.notifyDataSetChanged();
        // 有网时刷新数据
        if(Client.isNetworkConnect(this)) {
            swipe.post(new Runnable() {
            @Override
            public void run() {
                swipe.setRefreshing(true);
            }
        });
        }
    }

    // 是否显示发表框
    private void showTimelinebarView() {
        timeLineBarView.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) recyclerView.getLayoutParams();
        if (babyAndParent == null) {
            timeLineBarView.setVisibility(View.INVISIBLE);
            height = 0;
        } else {
            int permission = babyAndParent.getPermission();
            if (permission == 0) {
                timeLineBarView.setVisibility(View.INVISIBLE);
                height = 0;
            } else {
                height = getResources().getDimensionPixelSize(R.dimen.base_height);
            }
        }
        lp.setMargins(0, 0, 0, height);
        recyclerView.setLayoutParams(lp);
    }

    // 双击置顶
    @Override
    public void onDoubleClick() {
        recyclerView.scrollToPosition(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        agent.refreshBaby();
        avatarView.setSex(agent.getBaby().getGender());
        avatarView.setAvatar(ChZhRJUtils.getText(agent.getBaby().getImageUrl(), ""));
        txtBabyName.setText(ChZhRJUtils.getText(agent.getBaby().getNoteName(), agent.getBaby().getName() + "的成长日记"));
            txtBabyAge.setText(BabyUtil.getBabyDay(agent.getBaby(), System.currentTimeMillis()));
        // 刷新数据适配器
        adapter.notifyDataSetChanged();
    }

    // 处理相关事件
    @Subscribe
    @Override
    public void onEvent(BaseEvent event) {
        super.onEvent(event);
        if(event.getState() == BaseEvent.STATE_FAILURE) {
            tipShow(event.getMessage());
            swipe.setRefreshing(false);
            loadMore = false;
            return;
        }
        // 加载宝宝关注人信息
        if(event.getType() == BaseEvent.TYPE_LOAD_BABY_PARENT) {
            // 刷新日记信息
            parents = DatabaseManager.getInstance(this).queryParent(mLoginInfo.getBabyID());
            adapter.notifyDataSetChanged();
        }
        else if(event.getType() == BaseEvent.TYPE_BABY_DELETED) {
            DatabaseManager.getInstance(this).deleteBaby(mLoginInfo.getBabyID());
            // 宝宝被取消关注
            tipShow("您已取消了对该宝宝的关注");
            finish();
            return;
        }
        else if(event.getType() == BaseEvent.TYPE_PERMISSION_CHANGED) {
            // 日记本读写权限改变
            babyAndParent = DatabaseManager.getInstance(this).queryBabyAndParent(mLoginInfo.getUserID(), mLoginInfo.getBabyID());
            showTimelinebarView();
        }
        else if(event.getType() == BaseEvent.TYPE_RANGE_CHANGED) {
            // 获取本地数据
            agent.syncComplete();
            // 刷新适配器
            adapter.notifyDataSetChanged();
        }
        // 日记刷新同步
        else if(event.getType() == BaseEvent.TYPE_TIMELINE_SYNC) {
            BaseTimelineEvent syncTimelineEvent = (BaseTimelineEvent) event;
            // 同步成功
            int updateNumber = syncTimelineEvent.getUpdateNumber();
            if (updateNumber != 0) {
                if(updateNumber < Config.QUERY_LENGTH) {
                    adapter.setEnd(true);
                } else {
                    adapter.setEnd(false);
                }
                // 隐藏空视图
                emptyView.setVisibility(View.GONE);
                // tipShow("同步成功");
                Logger.d("同步数量" + updateNumber);
                // 获取本地数据
                agent.syncComplete();
                // 刷新适配器
                adapter.notifyDataSetChanged();
            } else {
                tipShow("已经是最新的数据了");
                if(agent.getDiscoverList().size() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                } else {
                    emptyView.setVisibility(View.GONE);
                }
            }
            swipe.setRefreshing(false);
        }
        // 日记加载更多
        else if (event.getType() == BaseEvent.TYPE_TIMELINE_LOAD_MORE) {
            System.out.println("加载完成");
            BaseTimelineEvent loadTimelineEvent = (BaseTimelineEvent) event;
            System.out.println("剩余数量：" + loadTimelineEvent.getLeftNumber());
            if (loadTimelineEvent.getUpdateNumber() != 0) {
                // 隐藏空视图
                emptyView.setVisibility(View.GONE);
                agent.loadComplete(loadTimelineEvent.getCreateTs());
                if(loadTimelineEvent.getUpdateNumber() < Config.QUERY_LENGTH) {
                    adapter.setEnd(true);
                } else {
                    adapter.setEnd(false);
                }
            } else {
                adapter.setEnd(true);
                tipShow("没有更早的数据了");
            }
            adapter.notifyDataSetChanged();
            loadMore = false;
            if(agent.getDiscoverList().size() == 0) {
                emptyView.setVisibility(View.VISIBLE);
            }
        }
        // 检查新评论后
        else if(event.getType() == BaseEvent.TYPE_CHECK_NEW_COMMENT) {
            System.out.println("刷新评论了");
            for(int i = 0; i < agent.getDiscoverList().size(); i++) {
                DTModel dtModel = agent.getDiscoverList().get(i);
                dtModel.setCommentList(DatabaseManager.getInstance(this).getDiscoverAllComments(dtModel.getDiscover().getDiaryID(), 1));
                dtModel.setLikeList(DatabaseManager.getInstance(this).getDiscoverAllComments(dtModel.getDiscover().getDiaryID(), 2));
            }
            adapter.notifyDataSetChanged();
            loadMore = false;
        }
    }

    @Override
    public void onRefresh() {
        // tipShow("刷新了");
        agent.requestBabyParentInfo();
        agent.startSync();
    }

    /**
     * 跳转到宝宝页面
     */
    public void startBabyActivity(View v) {

        // 当前宝宝的编号
        Intent intent = new Intent(this, BabyDiaryActivity.class);
//        intent.putExtra("babyId", agent.getBaby().getBabyID());
        startActivityForResult(intent, Config.REQUEST_OPEN_BABY_DIARY);
    }

    /**
     * 加载更多
     */
    private boolean loadMore = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_comment:
                requestComment();
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        commentLayout.setVisibility(View.INVISIBLE);
        showTimelinebarView();
        timeLineBarView.close();
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(recyclerView.getWindowToken(), 0);
        return false;
    }

    private class ExtraOnScrollListener extends RecyclerView.OnScrollListener {

        public ExtraOnScrollListener() {
            super();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if(adapter.getItemCount() > 0) {
                fixedDateLayout.setVisibility(View.VISIBLE);
                int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                // 显示日期
                Date date = new Date(agent.getDiscoverList().get(firstVisibleItem).getDiscover().getCreateTS());
                txtFixedDay.setText(String.valueOf(date.getDate()));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
                txtFixedDate.setText(dateFormat.format(date));
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            int lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
            int totalItemCount = recyclerView.getLayoutManager().getItemCount();
            if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                if (!loadMore) {
                    loadMore = true;
                    // 加载数据
                    System.out.println("加载了");
                    agent.loadMore();
                }
            }
            int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if(firstVisibleItem != -1) {
                // 显示日期
                Date date = new Date(agent.getDiscoverList().get(firstVisibleItem).getDiscover().getCreateTS());
                txtFixedDay.setText(String.valueOf(date.getDate()));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
                txtFixedDate.setText(dateFormat.format(date));
            }
        }
    }

    @Override
    public void onClickLeft() {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        onClickLeft();
    }

    @Override
    public void onClickRight() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            if (requestCode == Config.REQUEST_OPEN_TIMELINE_PHOTO || requestCode == Config.REQUEST_OPEN_TIMELINE_CAMERA) {
                // 发送照片日记
                sendPhoto(bundle.getString("theme"), bundle.getString("text"), bundle.getStringArray("urls"));
            } else if (requestCode == Config.REQUEST_OPEN_TIMELINE_VIDEO) {
                // 发送视频日记
                sendVideo(bundle.getString("screenshotUrl"), bundle.getInt("length"), bundle.getString("localUrl"));
            } else if (requestCode == Config.REQUEST_OPEN_TIMELINE_MILESTONE) {
                // 发送第一次日记
                sendMilestone(bundle.getString("milestone"), bundle.getInt("milestoneID"));
            } else if(requestCode == Config.REQUEST_OPEN_BABY_DIARY) {
                // 取消关注后，结束
                if(data != null && data.getBooleanExtra(Config.EXTRA_CAN_BACK, true)) {
                    finish();
                }
            }
        }
    }

    // -- 发表日记模块开始 --

    // 发表文字日记
    @Override
    public void sendMessage(String text) {

        // 隐藏空视图
        emptyView.setVisibility(View.GONE);

        agent.sendMessage(text);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);

        // 隐藏输入法
        InputMethodManager methodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        methodManager.hideSoftInputFromWindow(recyclerView.getWindowToken(), 0);
    }

    // 发送照片日记
    public void sendPhoto(String theme, String text, String[] urls) {

        // 隐藏空视图
        emptyView.setVisibility(View.GONE);

        agent.sendPhoto(theme, text, urls);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
    }

    // 发送音频日记
    public void sendAudio(int length, String path) {

        // 隐藏空视图
        emptyView.setVisibility(View.GONE);

        agent.sendAudio(length, path);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
    }

    // 发送视频日记
    public void sendVideo(String screenshotUrl, int length, String path) {

        // 隐藏空视图
        emptyView.setVisibility(View.GONE);

        agent.sendVideo(screenshotUrl, length, path);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
    }

    // 发表第一次日记
    public void sendMilestone(String milestone, int milestoneId) {

        // 隐藏空视图
        emptyView.setVisibility(View.GONE);

        agent.sendMilestone(milestone, milestoneId);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
    }

   // 更多里跳转对应的发表界面
    @Override
    public void execute(int position) {
        timeLineBarView.close();
        Intent intent;
        switch (position) {
            case Config.FUNCTION_PHOTO:
                intent = new Intent(this, TimelinePhotoActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_PHOTO);
                break;
            case Config.FUNCTION_CAMERA:
                intent = new Intent(this, TimelineCameraActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_CAMERA);
                break;
            case Config.FUNCTION_VIDEO:
                intent = new Intent(this, TimelineVideoActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_VIDEO);
                return;
            case Config.FUNCTION_FIRST:
                intent = new Intent(this, TimelineMilestoneActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_MILESTONE);
                break;
        }
    }

    // 开始录制音频
    @Override
    public void start() { }

    // 录制音频完成
    @Override
    public void success(int length, String path) {
        sendAudio(length, path);
    }

    private static final String SPACE = " ";

    @Override
    public void timing(int length) {
        tipShow(SPACE + SPACE + SPACE + "录音中" + SPACE + length + SPACE + SPACE + '\n' + "(上滑可以取消)");
    }

    @Override
    public void failure() {
        tipShow("录音失败");
    }

    @Override
    public void cancel() {
        tipShow("录音取消");
    }

    // -- 发表日记模块结束 --

    // -- 数据适配器模块开始 --

    @Override
    public void onClickPhoto(int position1, int position2) {
        Intent intent = new Intent(this, DiscoverGalleryActivity.class);
        intent.putExtra("photoUrls", photoUrl(position1));
        intent.putExtra("index", position2);
        startActivity(intent);
    }

    // 当前播放位置
    private int audioPlayPosition = -1;

    @Override
    public void onClickAudio(int position) {
        DTModel model;
        if (audioPlayPosition == position) {
            audioPlayPosition = -1;
            model = agent.getDiscoverList().get(position);
            if(model != null) {
                model.setIsAudioPlay(false);
            }
            adapter.notifyItemChanged(position);
            // 停止播放
            stopPlayback();
        } else {
            if (audioPlayPosition != -1) {
                model = agent.getDiscoverList().get(audioPlayPosition);
                if(model != null) {
                    model.setIsAudioPlay(false);
                }
                adapter.notifyItemChanged(audioPlayPosition);
                // 停止播放
                stopPlayback();
            }
            audioPlayPosition = position;
            model = agent.getDiscoverList().get(position);
            model.setIsAudioPlay(true);
            adapter.notifyItemChanged(position);
            // 开始播放
            playAudio(model);
        }
    }

    // 尝试下载音频
    @Override
    public void downloadAudio(final int position) {
        final DTModel model = agent.getDiscoverList().get(position);
        if(!TextUtils.isEmpty(model.getDiscover().getAudioLocalUrl()) && new File(model.getDiscover().getAudioLocalUrl()).exists()) {
            return;
        }
        String audioUrl = model.getDiscover().getAudio();
        if(audioUrl == null) {
            return;
        }
        int index = audioUrl.indexOf(Config.AUDIO);
        if(index == -1) {
            return;
        }
        String subUrl = audioUrl.substring(index);
        File file = new File(getExternalCacheDir(), String.valueOf(subUrl.hashCode()));
        if (!file.exists()) {
            Client.downloadFile(this, audioUrl, new FileAsyncHttpResponseHandler(file) {

                @Override
                public void onSuccess(int statusCode, Header[] headers, File file) {
                    DatabaseManager.getInstance(DiscoverTimelineActivity.this)
                            .updateDiscoverAudioLocalPath(file.getAbsolutePath(), model.getDiscover().getDiaryID());
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {

                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {

                }
            });
        }
    }

    // 当前播放
    private DTModel playModel = null;

    // 播放音频
    private void playAudio(final DTModel model) {

        Discover discover = model.getDiscover();
        player = new MediaPlayer();
        try {
            if(discover.getAudioLocalUrl() == null) {
                player.setDataSource(discover.getAudio());
            } else {
                player.setDataSource(discover.getAudioLocalUrl());
            }
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    model.setIsAudioPlay(false);
                    adapter.notifyDataSetChanged();
                    stopPlayback();
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlayback();
                    return true;
                }
            });
            player.prepare();
            player.start();
            playModel = model;
        } catch (IOException e) {
            e.printStackTrace();
            stopPlayback();
        }
    }

    // 停止播放
    @Override
    public void stopPlayback() {
        if (player == null) // we were not in playback
            return;
        player.stop();
        player.release();
        player = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(playModel != null) {
            playModel.setIsAudioPlay(false);
            adapter.notifyDataSetChanged();
        }
        stopPlayback();
    }

    @Override
    public void onClickVideo(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            Toast.makeText(this, "日记不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, TimelinePlayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("uuid", discover.getDiaryID());
        bundle.putString("url", discover.getVideo());
        intent.putExtras(bundle);
        startActivity(intent);

//        Intent intent = new Intent(this, DiscoverVideoActivity.class);
//        intent.putExtra("videoUrl", agent.getDiscoverList().get(position).getDiscover().getVideoLocalUrl());
//        startActivity(intent);
    }

    @Override
    public int length() {
        return agent.getDiscoverList().size();
    }

    @Override
    public String userName(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
      return discover.getMemberName();
    }

    @Override
    public String userId(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return discover.getUserID();
    }

    private int positionComment = -1, positionLayerComment = -1;
    private String targetUuid, targetName, targetNickname, targetUserId;

    // 发表评论
    @Override
    public void sendComment(int position) {
        positionComment = position;
        positionLayerComment = -1;
        targetUuid = "";
        targetName = "";
        targetNickname = "";
        commentLayout.setVisibility(View.VISIBLE);
        timeLineBarView.setVisibility(View.GONE);
        editComment.requestFocus();
        editComment.setHint(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    // 发表评论回复
    @Override
    public void sendComment(int pos1, int pos2) {
        positionComment = pos1;
        positionLayerComment = pos2;
        // 需要登录
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return;
        }
        DTModel dtModel = agent.getDiscoverList().get(pos1);
        String userId = mLoginInfo.getUserID();
        int num = 0;
        for (int i = 0; i < dtModel.getCommentList().size(); i++) {
            if (positionLayerComment == num) {
                if (userId.equals(dtModel.getCommentList().get(i).getUserID())) {
                    deleteDialog(dtModel.getCommentList().get(i));
                    return;
                } else {
                    targetUuid = dtModel.getCommentList().get(i).getIdentity();
                    targetName = dtModel.getCommentList().get(i).getMemberName();
                    targetNickname = dtModel.getCommentList().get(i).getUserNickname();
                    targetUserId = dtModel.getCommentList().get(i).getUserID();
                    break;
                }
            }
            num++;
        }
        commentLayout.setVisibility(View.VISIBLE);
        timeLineBarView.setVisibility(View.INVISIBLE);
        editComment.requestFocus();
        editComment.setHint("回复" + targetName);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    // 网络请求，发表评论
    private void requestComment() {
        if (TextUtils.isEmpty(editComment.getText())) {
            return;
        }
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return;
        }
        String phone = mLoginInfo.getPhone();
        String token = mLoginInfo.getToken().getAccessToken();
        String userId = mLoginInfo.getUserID();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(agent.getDiscoverList().get(positionComment).getDiscover().getBabyID());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();
        String nickname = mLoginInfo.getName();
        String diaryId = agent.getDiscoverList().get(positionComment).getDiscover().getDiaryID();
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String comment = editComment.getText().toString();

        // -------- 离线评论部分 Start ---------
        final DiscoverSaveComment saveComment = new DiscoverSaveComment();
        saveComment.setCommentType(1);
        saveComment.setDiaryID(diaryId);
        saveComment.setIdentity(uuid);
        saveComment.setUserID(userId);
        saveComment.setOperationState(1);
        saveComment.setMemberName(name);
        saveComment.setUserNickname(nickname);
        saveComment.setContent(comment);
        saveComment.setCreateTS(System.currentTimeMillis());
        saveComment.setUserHeadUrl(mLoginInfo.getUrl());
        saveComment.setIsNew(false);
        saveComment.setFrom(2);
        // -------- 离线评论部分 End ---------

        if (positionLayerComment != -1) {

            //---------- 离线评论部分 Start ---------
            saveComment.setReplyIdentity(targetUuid);
            saveComment.setReplyMemberName(targetName);
            saveComment.setReplyNickname(targetNickname);
            saveComment.setReplyUserID(targetUserId);
            // -------- 离线评论部分 End ---------
        }

        agent.getDiscoverList().get(positionComment).getCommentList().add(saveComment);
        DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
        adapter.notifyItemChanged(positionComment);

        commentLayout.setVisibility(View.INVISIBLE);
        showTimelinebarView();
        editComment.setText(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        // Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler(), networkUnavailableSampleImpl());
        Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                // 将评论保存到本地
                saveComment.setIsLocal(false);
                DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {
                // 离线时，存储离线评论，待有网的时候处理
                saveComment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        });
    }

    // 删除评论
    private void deleteDialog(final DiscoverSaveComment comment) {
        new AlertDialog.Builder(this).setTitle("删除该条评论?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                agent.getDiscoverList().get(positionComment).getCommentList().remove(comment);
                adapter.notifyItemChanged(positionComment);
                // requestDeleteComment(response.getId());
                requestDeleteComment(comment);
            }
        }).setNegativeButton("取消", null).show();
    }

    // 向网络请求删除评论
    private void requestDeleteComment(final DiscoverSaveComment comment) {
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return;
        }

        // 离线评论
        comment.setOperationState(0); // 取消评论
        DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);

        String phone = mLoginInfo.getPhone();
        String token = mLoginInfo.getToken().getAccessToken();
        Client.requestDeleteComment(this, phone, token, comment.getIdentity(), new ResponseHandler() {
            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).deleteComment(comment.getIdentity());
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {
                comment.setOperationState(0);
                comment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
            }
        });
    }

    // 发表赞
    @Override
    public void sendPraise(int position) {
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return;
        }
        String phone = mLoginInfo.getPhone();
        String token = mLoginInfo.getToken().getAccessToken();
        String userId = mLoginInfo.getUserID();
        String nickname = mLoginInfo.getName();
        DTModel dtModel = agent.getDiscoverList().get(position);
        Baby baby = DatabaseManager.getInstance(this).queryBaby(dtModel.getDiscover().getBabyID());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();
        final String diaryId = dtModel.getDiscover().getDiaryID();

        String uuid = null;
        int likeIndex = -1;
        boolean like = true;
        if (dtModel.getLikeList() == null || dtModel.getLikeList().size() == 0) {
            uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
        } else {
            for (int i = 0; i < dtModel.getLikeList().size(); i++) {
                if (userId.equals(dtModel.getLikeList().get(i).getUserID()) && dtModel.getLikeList().get(i).getOperationState() == 1) {
                    uuid = dtModel.getLikeList().get(i).getIdentity().toString();
                    likeIndex = i;
                    like = false;
                    break;
                }
            }
            if (like) {
                uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
            }
        }

        // ---------- 离线赞部分 Start -------------
        final DiscoverSaveComment comment = new DiscoverSaveComment();
        comment.setCommentType(2);
        comment.setUserHeadUrl(mLoginInfo.getUrl());
        comment.setIsNew(false);
        comment.setDiaryID(diaryId);
        comment.setIdentity(uuid);
        comment.setUserID(userId);
        comment.setMemberName(name);
        comment.setUserNickname(nickname);
        comment.setFrom(2);
        comment.setCreateTS(System.currentTimeMillis());
        // ---------- 离线赞部分 End -------------

        if (like) {

            dtModel.getLikeList().add(comment);
            comment.setOperationState(1);
            DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
            adapter.notifyItemChanged(position);

            // Client.requestLike(this, phone, token, diaryId, uuid, new ResponseHandler(), networkUnavailableSampleImpl());
            Client.requestLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    // 有网的时候存储到本地
                    comment.setIsLocal(false);
                    DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        } else {

            if (likeIndex != -1) {
                dtModel.getLikeList().remove(likeIndex);
                comment.setOperationState(0);
                DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                adapter.notifyItemChanged(position);
            }

            // Client.requestUnLike(this, phone, token, diaryId, uuid, new ResponseHandler(), networkUnavailableSampleImpl());
            final String commentId = uuid;
            Client.requestUnLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    // tipShow(value.toString());
                    DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).deleteComment(commentId);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverTimelineActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        }
    }

    @Override
    public String userUrl(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        // 判断发表人是否是当前登录用户，返回当前登录用户的头像
        if(discover.getUserID().equals(mLoginInfo.getUserID())) {
            return mLoginInfo.getUrl();
        }
        if(parents != null) {
            for (Parent parent : parents) {
                if (parent.getName().equals(discover.getMemberName())) {
                    return ChZhRJUtils.getText(parent.getPath(), "");
                }
            }
        }
        return ChZhRJUtils.getText(discover.getUserHeadUrl(), "");
    }

    @Override
    public long time(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return new Date().getTime();
        }
        return agent.getDiscoverList().get(position).getDiscover().getCreateTS();
    }

    @Override
    public boolean isLike(int position) {
        List<DiscoverSaveComment> likeList = agent.getDiscoverList().get(position).getLikeList();
        if (likeList == null || likeList.size() == 0) {
            return false;
        }
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return false;
        }
        String userId = mLoginInfo.getUserID();
        for (int i = 0; i < likeList.size(); i++) {
            if (userId.equals(likeList.get(i).getUserID())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String diaryId(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return discover.getDiaryID();
    }

    @Override
    public void removeDiary(int position) {
        agent.getDiscoverList().remove(position);
        adapter.notifyItemRemoved(position);
        adapter.notifyItemChanged(position);
    }

    @Override
    public boolean showBottom(int position) {
        return showLike(position) || showComment(position);
    }

    @Override
    public boolean showLike(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return false;
        }
        return agent.getDiscoverList().get(position).getLikeList() != null && agent.getDiscoverList().get(position).getLikeList().size() > 0;
    }

    @Override
    public ArrayList<String> likeList(int position) {
        ArrayList<DiscoverSaveComment> likeList = agent.getDiscoverList().get(position).getLikeList();
        if (likeList == null || likeList.size() == 0) {
            return null;
        }
        ArrayList<String> stringArrayList = new ArrayList<String>();
        for (int i = 0; i < likeList.size(); i++) {
            stringArrayList.add(likeList.get(i).getMemberName());
        }
        return stringArrayList;
    }

    @Override
    public boolean showComment(int position) {
        return agent.getDiscoverList().get(position).getCommentList() != null && agent.getDiscoverList().get(position).getCommentList().size() > 0;
    }

    @Override
    public ArrayList<DTAdapter.CommentModel> commentList(int position) {
        ArrayList<DiscoverSaveComment> commentList = agent.getDiscoverList().get(position).getCommentList();
        if (commentList == null || commentList.size() == 0) {
            return null;
        }
        ArrayList<DTAdapter.CommentModel> commentArrayList = new ArrayList<>();
        for (int i = 0; i < commentList.size(); i++) {

            DTAdapter.CommentModel model = new DTAdapter.CommentModel();
            model.setUserName1(commentList.get(i).getMemberName());
            model.setUserName2(commentList.get(i).getReplyMemberName());
            model.setContent(commentList.get(i).getContent());
            commentArrayList.add(model);
        }
        return commentArrayList;
    }

    @Override
    public String text(int position) {
        return agent.getDiscoverList().get(position).getDiscover().getText();
    }

    @Override
    public String photoLabel(int position) {
        return agent.getDiscoverList().get(position).getDiscover().getTheme();
    }

    @Override
    public String photoContent(int position) {
        return agent.getDiscoverList().get(position).getDiscover().getText();
    }

    @Override
    public String[] photoUrl(int position) {
        ArrayList<DiscoverPhoto> photoList = agent.getDiscoverList().get(position).getPhotoList();
        String[] photos = new String[photoList.size()];
        for(int i = 0; i < photoList.size(); i++) {
            photos[i] = photoList.get(i).getUrl();
        }
        return photos;
    }

    @Override
    public String theme(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return discover.getTheme();
    }

    @Override
    public int audioLength(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return 0;
        }
        return discover.getDuration();
    }

    @Override
    public boolean audioPlay(int position) {
        return agent.getDiscoverList().get(position).isAudioPlay();
    }

    @Override
    public String thumbnailUrl(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return discover.getScreenshot();
    }

    @Override
    public String milestone(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return discover.getMilestone();
    }

    @Override
    public String age(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return "";
        }
        return BabyUtil.getBabyDay(agent.getBaby(), discover.getGrowthStageID(), discover.getCreateTS());
//        switch (discover.getGrowthStageID()) {
//            case Client.STATE_READY:
//                return "备孕中";
//            case Client.STATE_START:
//                if (agent.getBaby().getDueDate() != 0) {
//                    return BabyUtil.getBabyDayByDueDateOrLastDate(agent.getBaby().getDueDate() - 280 * 24 * 60 * 60 * 1000l, discover.getCreateTS());
//                } else {
//                    return BabyUtil.getBabyDayByDueDateOrLastDate(agent.getBaby().getLastDate(), discover.getCreateTS());
//                }
//            case Client.STATE_END:
//                return BabyUtil.getBabyDayByBirthday(agent.getBaby().getBirthday(), discover.getCreateTS());
//        }
//        return "";
    }

    @Override
    public int type(int position) {
        Discover discover = agent.getDiscoverList().get(position).getDiscover();
        if(discover == null) {
            return 0;
        }
        if (discover.getType() == 1) {
            if (TextUtils.isEmpty(discover.getMilestone())) {
                return 0;
            } else {
                return 4;
            }
        }
        return discover.getType() - 1;
    }

    // -- 数据适配器模块结束 --
}
